<script>
  import $ from '../dfish.js'
  import {
    h
  } from "vue"
  import Dialog from './Dialog.vue'
  import MenuButton from './MenuButton.vue'
  import Vertical from './Vertical.vue'
  
  let inst = null

  export default {
    name: 'w-menu',
    mixins: [Dialog],
    methods: {
      x_default() {
        return {
          autoHide: true,
          independent: true,
        }
      },
      hasBubble(a, b) {
        if (this.contains(a, b)) return true
        let p = $(a)
        if (p && (p = p.parentMenu) && p.rootCommander == this.rootCommander) return true
      },
      setMaxHeight(h) {
        h -= 38
        this.maxHeight = h - (h % 32) + 38
      },
      arrow(a) {
        let b = this.$refs.bbr.el()
        let c = $.bcr(b)
        b.scrollTop += c.height * a
      },
      mousewheel(e) {
        this.arrow(e.wheelDelta < 0 ? 1 : -1)
      },
      getRoot() {
        let c = this
        while (c.getCommander().$options.name === 'w-menubutton') c = c.getCommander().parentMenu
        return c
      },
      html_buttons() {
        return this.slots_children().map(s => {
          let n = s.type.name
          return n === 'w-button' || n === 'w-submitbutton' ? h(MenuButton, s.props, s.children) : s
        })
      },
      html_slots() {
        return [
          this.maxHeight && h('div', {class: 'w-menu-arr f-oh', onclick: e => this.arrow(-1)}, h('i', {class: 'f-i f-i-caret-up'})),
          h(Vertical, {class: 'w-menu-bbr', height: '*', ref: 'bbr', onwheel: this.mousewheel}, {default: () => this.html_buttons()}),
          this.maxHeight && h('div', {class: 'w-menu-arr f-oh', onclick: e => this.arrow(1)}, h('i', {class: 'f-i f-i-caret-down'})),
        ]
      }
    },
    computed: {
      html_class() {
        return ['w-dialog w-vertical', this.animateClass, this.snapClass, this.x.dropClass, {
          'z-hide': this.isDeactivated,
          'z-full': this.x.fullScreen,
          'z-max-height': this.maxHeight,
        }]
      },
      root() {
        return this.getRoot()
      },
      rootCommander() {
        return this.root.commander
      },
    },
    mounted() {
      if (this.isEntity) {
        if (this.context && this.context.$options.name !== 'w-menubutton') {
          if (inst) {
            $.close(inst)
          }
          inst = this
        }

      }
    }
  }
</script>

<style>
  .w-menu {
    box-shadow: none;
    border: 1px solid #ccc;
    background: #fff;
  }
  .w-menu .w-split {
    height: 1px;
    background: #ddd;
    margin: 2px 0;
  }
  .w-menu-arr {
    height: 18px;
    line-height: 1;
    text-align: center;
    cursor: pointer;
  }
  .w-menu-arr:hover {
    background: #f5f5f5;
  }
</style>
